<?php

/**
 * 管理员模型
 *
 * @author JiangJian <silverd@sohu.com>
 * @copyright 2011-2012 xiangle.com
 * $Id: Admin.php 162 2012-11-09 04:04:30Z Jun.Lu.726@gmail.com $
 * @version    2012-02-14  ::  JiangJian  ::  Create File
 */
class Model_System_Admin extends Model_AbstractDao
{

    protected $_dbName     = 'BingoMobi';
    protected $_tableName  = 'bg_sys_admin';
    protected $_primaryKey = 'admin_id';
    protected $_nameField  = 'admin_name';

    /**
     * 获取单条完整信息（包含角色信息）
     *
     * @param mixed $whereArr
     * @return array
     */
    public function getRowFull($whereArr)
    {
        $whereSql = Com_DB::getWhereSQL($whereArr);
        return $this->_db()->fetchRow("SELECT a.*, r.* FROM `bg_sys_admin` AS a
            INNER JOIN `bg_sys_role` AS r ON (a.role_id = r.role_id)
            WHERE {$whereSql}");
    }

    /**
     * 检测数据合法性
     *
     * @param array $data
     * @return true|string
     */
    public function checkInvalid($data)
    {
        if (!$data['admin_name'] || !$data['email'] || !$data['mobile']) {
            return '用户名、邮箱、手机三者必填';
        }

        if (!$data['role_id']) {// !$data['city_id'] || 所属城市、
            return '请选择所属角色';
        }

        if (!Helper_Check::isEmail($data['email'])) {
            return '邮箱格式不对';
        }

        if (!Helper_Check::isMobile($data['mobile'])) {
            return '手机号码格式不对';
        }

        return true;
    }

    /**
     * 检测数据重复
     *
     * @param array $data
     * @param int $adminId 原用户uid
     * @return true|string
     */
    public function checkRepeat($data, $adminId = 0)
    {
        $theOne = $this->row(array('admin_name' => $data['admin_name']));
        if ($theOne) {
            if (!$adminId || ($adminId > 0 && $theOne['admin_id'] != $adminId)) {
                return '该用户名已存在，请更换';
            }
        }

        $theOne = $this->row(array('email' => $data['email']));
        if ($theOne) {
            if (!$adminId || ($adminId > 0 && $theOne['admin_id'] != $adminId)) {
                return '该邮箱已存在，请更换';
            }
        }

        $theOne = $this->row(array('mobile' => $data['mobile']));
        if ($theOne) {
            if (!$adminId || ($adminId > 0 && $theOne['admin_id'] != $adminId)) {
                return '该手机已存在，请更换';
            }
        }

        return true;
    }

    /**
     * 添加一条
     *
     * @param array $data
     * @return bool
     */
    public function add($data, &$insertId = 0)
    {
        $data = Helper_String::deepFilterDatas($data, array('trim', 'strip_tags'));

        // 检测字符合法性
        $result = $this->checkInvalid($data);
        if ($result !== true) {
            return $result;
        }

        if (!$data['password']) {
            return '密码不能为空';
        }

        // 检测重复
        $result = $this->checkRepeat($data);
        if ($result !== true) {
            return $result;
        }

        $setArr = array(
            'admin_name'  => $data['admin_name'],
            'email'       => $data['email'],
            'mobile'      => $data['mobile'],
            'password'    => md5($data['password']),
            'role_id'     => intval($data['role_id']),
            'city_id'     => intval($data['city_id']),
            'create_time' => time(),
        );

        $insertId = $this->_db()->insert('bg_sys_admin', $setArr);
        if ($insertId < 1) {
            return '入库失败';
        }

        return true;
    }

    /**
     * 更新一条
     *
     * @param int $adminId
     * @param array $data
     * @return bool
     */
    public function updateOne($adminId, $data)
    {
        $adminId = intval($adminId);
        if ($adminId < 1) {
            return '非法的用户id';
        }

        $data = Helper_String::deepFilterDatas($data, array('trim', 'strip_tags'));

        // 检测字符合法性
        $result = $this->checkInvalid($data);
        if ($result !== true) {
            return $result;
        }

        // 检测重复
        $result = $this->checkRepeat($data, $adminId);
        if ($result !== true) {
            return $result;
        }

        $setArr = array(
            'admin_name' => $data['admin_name'],
            'email'      => $data['email'],
            'mobile'     => $data['mobile'],
            'role_id'    => intval($data['role_id']),
            'city_id'    => intval($data['city_id']),
        );

        // 修改密码
        if ($data['password']) {
            $setArr['password'] = md5($data['password']);
        }

        if (!$this->_db()->update('bg_sys_admin', $setArr, "admin_id = '{$adminId}'")) {
            return '更新用户入库失败';
        }

        return true;
    }

    /**
     * 更新最后登录信息
     *
     * @param int $adminId
     * @return bool
     */
    public function updateLastLogin($adminId)
    {
        $adminId = intval($adminId);
        if ($adminId < 1) {
            return false;
        }

        $setArr = array(
            'last_login' => time(),
            'last_ip'    => Helper_Client::getUserIp(),
        );

        return $this->_db()->update('bg_sys_admin', $setArr, "admin_id = '{$adminId}'");
    }

    /**
     * 更新我的密码
     *
     * @param array $authUser
     * @param array $data
     * @return bool/string
     */
    public function updatePassword($authUser, $data)
    {
        $adminId = $authUser['admin_id'];
        if ($adminId < 1) {
            return '非法的用户id';
        }

        $data = Helper_String::deepFilterDatas($data, array('trim', 'strip_tags'));

        $oldPassword     = $data['old_password'];
        $newPassword     = $data['new_password'];
        $confirmPassword = $data['confirm_password'];

        if (!$oldPassword || !$newPassword || !$confirmPassword) {
            return '原密码、新密码、重复密码不能为空';
        }

        if ($newPassword != $confirmPassword) {
            return '两次输入的密码不一样';
        }

        if (md5($oldPassword) != $authUser['password']) {
            return '原密码不正确';
        }

        $setArr = array(
            'password' => md5($newPassword)
        );

        if (!$this->_db()->update('bg_sys_admin', $setArr, "admin_id = '{$adminId}'")) {
            return '更新密码入库失败';
        }

        return true;
    }

}